import { Component, OnInit } from '@angular/core';
import {ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {FormValidatorService, GreatModalService} from "great-ngform";

@Component({
  selector: 'app-can-leave',
  templateUrl: './can-leave.component.html',
  styleUrls: ['./can-leave.component.less']
})
export class CanLeaveComponent implements OnInit {

  form: FormGroup;

  constructor(
    private fb: FormBuilder,
    private formValidatorService: FormValidatorService,
    private greatModalService: GreatModalService) { }

  ngOnInit() {
    this.form = this.fb.group({
      name: new FormControl(null, [
        this.formValidatorService.chinese({maxLength:10})
      ]),
      age: new FormControl(null, [
        this.formValidatorService.integer({maxLength:3})
      ])
    });
  }

  canDeactivate(
    component?: any,
    currentRoute?: ActivatedRouteSnapshot,
    currentState?: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean> | boolean {
    if(this.form.dirty){
      return this.greatModalService.openDialog(
        (save) => {
          const flag = Math.random() * 10 > 4; // 随机生成一个值，表示后台保存成功或失败
          save(flag);
        },
        (cancle) => {
          cancle();
        });
    }
    return true;
  }

}
